package com.gehj.androidlibs;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.util.Consumer;

import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

import com.gehj.alluitls.androidUtils.LogUtil;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;


import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @ClassName: MainRxActivity
 * @Description: rxjava展示
 * @Author: gehj
 * @CreateDate: 2020/12/15 17:14
 */

public class MainRxActivity extends AppCompatActivity {
    private TextView textViewData;
    private Disposable disposable;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_rx);

        textViewData = (TextView) findViewById(R.id.textView_data);

        //Rxjava1(); //线程睡觉


        disposable = Observable.create(new ObservableOnSubscribe<String>() {
            OkHttpClient client = new OkHttpClient();

            @Override
            public void subscribe(@NotNull ObservableEmitter<String> emitter) {
                Response response = null;
                try {
                    response = client.newCall(new Request.Builder().
                            url("https://www.baidu.com").build()).execute();
                    if (response.isSuccessful()) { //子线程处理response;
                        if (!emitter.isDisposed()) { //true 代表 已经解除订阅
                            emitter.onNext(response.body().string());
                        }
                        emitter.onComplete();

                    } else if (!response.isSuccessful() && !emitter.isDisposed()) {
                        emitter.onError(new Exception(response.message()));
                    }

                } catch (IOException e) {
                    emitter.onError(e);
                }

            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new io.reactivex.functions.Consumer<String>() {
                    @Override
                    public void accept(String json) throws Exception {
                        //UI线程处理
                        textViewData.setText(json);
                    }
                }, new io.reactivex.functions.Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        LogUtil.e("throwable", throwable.getMessage());
                    }
                });


    }

    private void Rxjava1() {
        //Observable被观察者：subscribe 子线程执行耗时操作；
        Observable<Integer> observable = Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
                Thread.sleep(2000);
                emitter.onNext(1);
            }
        });

        //Consumer执行主线(UI)程操作
        Consumer<Integer> consumer = new Consumer<Integer>() {
            @Override
            public void accept(Integer integer) {
                Intent intent = new Intent(getApplicationContext(), MainActivity_handler.class);
                startActivity(intent);
                finish();
            }
        };

        //observable 被观察者
        observable.subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread()) //mainThread()是Observer观察者
                .subscribe((Observer<? super Integer>) consumer); //在consumer订阅的，observable一有变化，状态改变，就会通知consumer执行


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        disposable.dispose(); //为了防止内存泄漏 取消请求
    }
}